<?php
App::import('Sanitize');
class ProductsController extends AppController {

/**
 * Controller name
 *
 * @var string
 * @access public
 */
	var $name = 'Products';
	 var $paginate = array(
    'limit' => 20,
      'order' => array('Product.created' => 'desc')
	);

	var $uses =array('Product', 'Comment', 'User', 'Manufacturer', 'Category', 'Rating', 'Deal', 'Viewhistory', 'Buyhistory');
/**
 * Default helper
 *
 * @var array
 * @access public
 */
	var $helpers = array('Html', 'Session','Thumb');
	var $components = array('Auth','Seo');

/**
 * This controller does not use a model
 *
 * @var array
 * @access public
 */

	function beforeFilter() {
		parent::beforeFilter();
		$allowedImgTypes = array("image/png", "image/jpeg", "image/gif");
		$this->set(compact('allowedImgTypes'));
	}
	function beforeRender()
	{
		parent::beforeRender();
		if(in_array($this -> params['action'],array("view")))
		{
			@$this->Seo->configureMeta($this->meta_url);
			@$this->set('title_for_layout', $this->Seo->getStr('page_title',$this->page_title));
			@$this->set('meta_title', $this->Seo->getStr('page_title', $this->meta_title));
			@$this->set('meta_keywords', $this->Seo->getStr('meta_keywords', $this->meta_keywords));
			@$this->set('meta_description', $this->Seo->getStr('meta_description', $this->meta_description));
			// debug($this->meta_description);
		}
	}
	
	
	function index() {
		if ($this->Session->check('Search.manufacturer'))
			$this->Session->delete('Search.manufacturer');
		if ($this->Session->check('Search.category'))
			$this->Session->delete('Search.category');

		$this->Session->write('Search.page', 1);
		
		$config =& Configure::getInstance();
		$types = $config->types;
		
		$products = $this -> getSearchResult('%');
		$this->set('products',$products);
	}
	
	//V-protocol functions

	function category() {
		$this->Session->write('Search.page', 1);

		$categories = $this->Category->find('all', array('order' => 'id'));
		$manufacturers = $this->Manufacturer->find('all');
		$products = $this->getSearchResult('%');

		$selected_categories = $this->Session->read('Search.category');
		$selected_manufacturers = $this->Session->read('Search.manufacturer');

		if (null == $selected_categories) $selected_categories = array();
		if (null == $selected_manufacturers) $selected_manufacturers = array();
		$this->set(compact(array('products', 'categories', 'manufacturers', 'selected_categories', 'selected_manufacturers')));
	}

	private function getSearchResult($keyword) {
		$condition = array(
			// 'Product.type' => 2,
			// 'Product.status' => 1,> 2,
			// 'Product.status' => 1,
			'AND' => array(
				'OR' => array(
					'Product.name LIKE' => $keyword,
					'Product.description LIKE' => $keyword
				)
			)
		);

		if ($this->Session->check('Search.manufacturer')) {
			$manufacturers = $this->Session->read('Search.manufacturer');
			$condition['AND'][] = array('manufacturer_id' => $manufacturers);
		}

		if ($this->Session->check('Search.category')) {
			$categories = $this->Session->read('Search.category');
			$condition['AND'][] = array('category_id' => $categories);
		}

		$this->paginate['conditions'] = $condition;
		$this->paginate['limit'] = 9;
		$this->paginate['page'] = $this->Session->read('Search.page');

		$search_order = $this->Session->read('Search.sort');
		switch ($search_order) {
			case 'newest':
				$this->paginate['order'] = 'Product.created DESC';
				break;
			case 'popular':
				$this->paginate['order'] = 'view_count DESC';
				break;
			case 'rating':
				$this->paginate['order'] = 'rating DESC';
				break;
		}

		$products = $this -> paginate();
		foreach($products as $key=>$product){
				$id = $product['Product']['id'];
				$url='/testimonies/view/'.$id;
				$comment_count=$this->Comment->find('count',array('conditions'=>array('Comment.url' => $url)));
				$products[$key]['Product']['comment_count'] = $comment_count;
		}
		if (count($products) > 0) {
			$products[0]['current_page'] = $this->Session->read('Search.page');
			$products[0]['total_page'] = ceil($this->Product->find('count', array('conditions' => $condition)) / $this->paginate['limit'] - 1e-6);
		}
		return $products;
	}

	function search() {
		if ($this->Session->check('Search.manufacturer'))
			$this->Session->delete('Search.manufacturer');
		if ($this->Session->check('Search.category'))
			$this->Session->delete('Search.category');

		$this->Session->write('Search.page', 1);

		$search_order = $this->Session->read('Search.sort');
		if ($search_order == '') $search_order = 'newest';
		$this->set('search_order', $search_order);

		$keyword = '%' . $this->data['Product']['keyword'] . '%';
		$this->set('keyword',$this->data['Product']['keyword']);
	}

	function ajaxSearch($keyword = '') {
		$this->autoRender = false;
		$products = $this->getSearchResult('%'.$keyword.'%');
		print_r(json_encode($products));
	}
	
	// End of V-protocol functions
	
	function map(){
		// $this->set('products', $this->Product->find('all'));
		$config =& Configure::getInstance(); 
		$types = $config->types;
		$product_sql = "SELECT `Product`.`id`, `Product`.`user_id`, `Product`.`name`, `Product`.`image`, `Product`.`latitude`, `Product`.`longtitude`, `User`.`id`, `User`.`facebook_id`, `User`.`name`, `User`.`username`, `User`.`avatar`, `Product`.`description`, `Product`.`type`
					FROM `products` AS `Product`
					LEFT JOIN `users` AS `User` ON (`Product`.`user_id` = `User`.`id`)
					WHERE (`Product`.`latitude` IS NOT NULL OR `Product`.`longtitude` IS NOT NULL)
					ORDER BY `Product`.`created` DESC";
		
		$products = $this->Product->query($product_sql);
		foreach($products as $key=>$product){
			$type_id = $product['Product']['type'];
			$products[$key]['Product']['type_name'] = $types[$product['Product']['type']];
			$products[$key]['Product']['description'] = substr(Sanitize::html($product['Product']['description'], array('remove' => true)), 0, 50) . ' ...';
		}
		$this->set('products', $products);
		// debug($products);
	}
	
	function homepage(){ // homepage
		$best_selling = $this->Product->find('all', array(
			'fields' => array('name', 'image', 'id'),
			'order' => array('Product.rating DESC'),
			'limit' => 10
		));
		$most_viewed = $this->Product->find('all', array(
			'fields' => array('name', 'image', 'id'),
			'order' => array('Product.view_count DESC'),
			'limit' => 10
		));
		$this->set(compact(array('best_selling', 'most_viewed')));
	}

	function ajaxSearchOption($option = null, $id = null) {
		$this->autoRender = false;

		switch ($option) {
			case 'page':
				$this->Session->write('Search.page', $id);
				print_r('Reloading page..');
				break;
			case 'newest':
				$this->Session->write('Search.sort', 'newest');
				print_r('Sorting product by releasing date');
				break;
			case 'rating':
				$this->Session->write('Search.sort', 'rating');
				print_r('Sorting product by rating');
				break;
			case 'popular':
				$this->Session->write('Search.sort', 'popular');
				print_r('Sorting product by popularity');
				break;
			case 'manufacturer':
				if (!$this->Session->check('Search.manufacturer')) {
					$manufacturers = array($id);
				} else {
					$manufacturers = $this->Session->read('Search.manufacturer');
					if (false == array_search($id, $manufacturers))
						$manufacturers[] = $id;
				}
				$this->Session->write('Search.manufacturer', $manufacturers);
				print_r('Filtering by manufacturer');
				break;
			case 'remove_manufacturer':
				$manufacturers = $this->Session->read('Search.manufacturer');
				unset($manufacturers[array_search($id, $manufacturers)]);
				if (count($manufacturers) == 0) {
					$this->Session->delete('Search.manufacturer');
				} else {
					$this->Session->write('Search.manufacturer', $manufacturers);
				}
				print_r('Removing filter by manufacturer');
				break;
			case 'remove_category':
				$categories = $this->Session->read('Search.category');
				unset($categories[array_search($id, $categories)]);
				if ($categories == array()) {
					$this->Session->delete('Search.category');
				} else {
					$this->Session->write('Search.category', $categories);
				}
				print_r('Removing filter by category');
				break;
			case 'category':
				if (!$this->Session->check('Search.category')) {
					$categories = array($id);
				} else {
					$categories = $this->Session->read('Search.category');
					$categories[] = $id;
				}
				$this->Session->write('Search.category', $categories);
				print_r('Filtering by category');
				break;
			case 'default':
				print_r('There was some error processing your request');
				break;
		}
	}

	function ajaxView($id = null) {
		$this->autoRender = false;
		if (!$id) {
			print_r('Some error occurred');
			return ;
		}
		$product = $this->Product->findById($id);
		if ($product == null) {
			print_r('Product does not exist');
			return ;
		}

		$result['title'] = $product['Product']['name'];
		$result['company'] = $product['Manufacturer']['name'];
		$result['company_url'] = $product['Manufacturer']['url'];

		$prices = $this->Deal->find('list', array(
			'fields' => 'price',
			'conditions' => array('Deal.product_id' => $product['Product']['id'])
		));
		if (count($prices) == 0) $prices[] = 1000;

		$min_price = 1000111000;
		$max_price = -1;
		foreach($prices as $p) {
			$min_price = min($min_price, $p);
			$max_price = max($max_price, $p);
		}

		$result['price'] = array($min_price, $max_price);
		$result['description'] = $product['Product']['description'];

		$result['status'] = "In stock";

		$result['image'] = array('img/posts/'.$product['Product']['image']);

		for($i = 2; $i <= 5; ++$i)
			if (null != $product['Product']['image'.$i]) {
				$result['image'][] = 'img/posts/'.$product['Product']['image'.$i];
			}

		$result['seller'] = array();

		print_r(json_encode($result));
	}
	
	function view($id=null) {
		if ($id > 100) {
			$this->redirect('/');
		}
		if (!$id) {
			$this->Session->setFlash(__('The product does not exist.', true));
			$this->redirect(array('action' => 'index'));
		}
		
		$this->Product->bindModel(
			array('hasMany' => array(
					'Deal' => array(
						'className' => 'Deal',
						'fields' => 'status',
						'conditions' => array('Deal.status' => IN_STOCK),
						'limit' => 1
					)
				)
			)
		);

		$product = $this->Product->findById($id);
		if ($product == null) {
			$this->Session->setFlash('Invalid url');
			$this->redirect('/');
		}
		
		$this->Product->unbindModel(
			array('hasMany' => array('Deal'))
		);

		$deals = $this->Deal->find('all', array(
			'conditions' => array('product_id' => $id, 'Deal.status' => '0'),
			'limit' => 9
		));
		$this->set('deals', $deals);
		
		$deals_price = $this->Deal->find('list', array(
			'fields' => array('Deal.price'),
			'conditions' => array('product_id' => $id, 'status' => '0')
			// ,'order' => array('Deal.price')
		));
		sort($deals_price);
		$this->set('deals_price', $deals_price);

		$this->Product->create();
		$product['Product']['view_count']++;
		$rating_list = $this->Rating->find('list', array(
			'conditions' => array('Rating.product_id' => $product['Product']['id']),
			'fields' => 'value'
		));

		if (null == $rating_list) {
			$product['Product']['rating'] = 3;
		}
		else {
			$cnt = 0; $sum = 0;
			foreach($rating_list as $r) {
				++$cnt;
				$sum += $r;
			}
			$product['Product']['rating'] = $sum / (float)$cnt;
		}
		$this->Product->save($product);

		if ($product == null) {
			$this->Session->setFlash(__('The product does not exist.', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('Product', $product);
		$url='/products/view/'.$id;
		$comment_count=$this->Comment->find('count',array('conditions'=>array('Comment.url' => $url)));
		//get previous and next page id:
		$neighbors=$this->Product->find('neighbors',array('field' => 'id', 'value' => $id));
		//debug($neighbors);
		//debug($product);
		$user=$this->Auth->user();
		if($user&&$user['User']['role']!= NORMAL) {
			$this->set('showedit',true);
		}
		else{
			$this->set('showedit',false);
		}

		if ($user) {
			$recently_view_products = $this->Viewhistory->find('all', array(
				'conditions' => array('Viewhistory.user_id' => $user['User']['id']),
				'fields' => array('Viewhistory.created', 'Product.id', 'Product.image', 'Product.name'),
				'limit' => 3,
				'order' => 'Viewhistory.created DESC'
			));

			$ok = true;
			foreach($recently_view_products as $r) {
				if ($r['Product']['id'] == $product['Product']['id'])
					$ok = false;
			}
			if ($ok) {
				$this->Viewhistory->create();
				$this->Viewhistory->save(array('Viewhistory' => array(
					'user_id' => $user['User']['id'],
					'product_id' => $product['Product']['id']
				)));
			}
		}
		else $recently_view_products = array();

		$related = $this->getSimilarProducts(array('0' => $product));

		$this->set(compact('comment_count', 'neighbors', 'recently_view_products', 'deals', 'related'));
		
		//meta
			@$urlexists = $this -> Seo->checkURLExists(  $this->params['url']['url']);
		
			if(!$urlexists)
			{
				@$this->meta_url = $type.'_view';
			}
			else
			{
				@$this -> meta_url = $this->params['url']['url'];
			}
			
			$remove_char = array('&amp;', 'nbsp;');
			$tplvars = array(
				"Name" => $product['Product']['name'],
				"Description" => str_replace($remove_char, '', Sanitize::html($product['Product']['description'], array('remove' => true)))
			);

			$this->page_title =
			$this->meta_title =
			$this->meta_keywords =
			$this->meta_description =$tplvars;
	}

	function add($type=null) {
		$user=$this->Auth->user();
		if(!$user || $user['User']['role'] == 1){
			$this->redirect(array('controller'=>'users','action'=>'login'));
		}
		$categories = $this->Category->find('list', array(
			'order' => 'id',
			'fields' => array('id', 'name')));
		$manufacturers = $this->Manufacturer->find('list', array(
			'order' => 'id',
			'fields' => array('id', 'name')
			));
		$this->set(compact('categories', 'manufacturers'));
		if (!empty($this->data)) {
			// debug($this->data);
			//image:
			if (isset($this->data['Product']['image_form']) && $this->data['Product']['image_form']) {
				$this->data['allowedImgTypes'] = $this->viewVars['allowedImgTypes'];

				$tmpFile = $this->data['Product']['image_form']['tmp_name'];
				$ext = end(explode("/", $this->data['Product']['image_form']['type']));
			 }
			 
			$this->Product->create();
			$this->data['Product']['user_id']=$user['User']['id'];
			if ($this->Product->save($this->data)) {
				$rId = $this->Product->getLastInsertID();

				if (isset($tmpFile) && $tmpFile) {
				  // check for directory for image upload
				  $folder = IMAGES . "posts/";
				  if (!file_exists($folder)) {
					mkdir($folder, 0777);
				  }

				  $this->data["Product"]["image"] = md5($rId). "." . $ext;
				  $this->data["Product"]["id"] = $rId;
				 //debug($this->data);
				  $this->Product->save($this->data); // save image value 


				  $myFile = "$folder/" . md5($rId) . "." . $ext;
					move_uploaded_file($tmpFile, $myFile);
				  // if (move_uploaded_file($tmpFile, $myFile)) {
					// $img = new ImageComponent();
					// $img->resize($myFile, $myFile, 200, 100, 100); // 200 x 100 quality 100
				  // }
				}
				$url='/products/view/'.$rId;
				$this->Session->setFlash(__('The product has been saved', true));
				$this->redirect($url);
			}
			else {
					$this->Session->setFlash(__('The product could not be saved. Please, try again.', true));
			}
		}
	}//end of add
	
	function edit($id=null) {
		if(!$id){
			 $this->redirect(array('action'=>'index'));
		}
		
		$product=$this->Product->findById($id);
		$this->set('id', $id);
		$categories = $this->Category->find('list', array(
			'order' => 'id',
			'fields' => array('id', 'name')));
		$manufacturers = $this->Manufacturer->find('list', array(
			'order' => 'id',
			'fields' => array('id', 'name')
			));
		$this->set(compact('categories', 'manufacturers'));

		$user=$this->Auth->user();
		if($user && $user['User']['role'] != NORMAL) {
		}
		else{
			$this->redirect(array('action'=>'index'));
		}
	
		if (!empty($this->data)) {
			$rId =  $id;

			for($image = 1; $image <= 5; ++$image) {
				$name_encode[$image] = md5($rId.time() * $image);
				$id = $image; if ($image == 1) $id = '';
				if (isset($this->data['Product']['image_form'.$id]) && $this->data['Product']['image_form'.$id]) {
					$this->data['allowedImgTypes'] = $this->viewVars['allowedImgTypes'];
					$tmpFile[$image] = $this->data['Product']['image_form'.$id]['tmp_name'];
				}
				if (isset($tmpFile[$image]) && $tmpFile[$image]) {
					$ext[$image] = end(explode("/", $this->data['Product']['image_form'.$id]['type']));
					$this->data["Product"]["image".$id] = $name_encode[$image]. "." . $ext[$image];
				}
			}

			if ($this->Product->save($this->data)) {
				for($image = 1; $image <= 5; $image++) {
				 $id = $image; if ($image == 1) $id = '';
				 if (isset($tmpFile[$image]) && $tmpFile[$image]) {
				  // check for directory for image upload
				  $folder = IMAGES . "posts/";

				  if (!file_exists($folder)) {
					mkdir($folder, 0777);
				  }

				  // delete previous files if any
				  $ref = $folder . "/" . $name_encode[$image] . ".*";
				  $glob = glob($ref);
				  foreach (glob("{$ref}*") as $filename) {
					@unlink($filename);
		//            echo $filename . "|";
				  }
				  //also need to delete cache image(thumbnail)
				/*  
				$cacheFilename = md5($this->data["Product"]["image"].'_w_x_h_210_150_n');
				 $cacheFile=IMAGES .'cache/thumbs/'.$cacheFilename.".*";
				   $glob = glob($cacheFile);
				  foreach (glob("{$cacheFile}*") as $filename) {
					@unlink($filename);
		//            echo $filename . "|";
				  }
				 */
				  
				  $myFile[$image] = "$folder/" . $name_encode[$image] . "." . $ext[$image];
				  move_uploaded_file($tmpFile[$image], $myFile[$image]);
				}
				}
				$this->Session->setFlash(__('The product has been saved', true));
				$url='/products/view/'.$rId;
				$this->redirect($url);
			  
			}
			else{
				$this->Session->setFlash(__('The product could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)&&$id!=null) {
		
			$this->data = $this->Product->findById($id);
			
		}
		

	}//end of edit
	function delete($id=null){
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for product', true));
			$this->redirect(array('action'=>'index'));
		}
		$cnt_deal = $this->Deal->find('count', array('conditions' => array(
			'product_id' => $id
		)));
		if ($cnt_deal > 0) {
			$this->Session->setFlash(__('Cannot delete product. This product already has some deal(s)', true));
			$this->redirect($this->referer());
		}
		$product = $this->Product->read(null, $id);
		
		$user=$this->Auth->user();
		if($user&&($user['User']['id']==$product['Product']['user_id']||$user['User']['role'] != NORMAL)){
		}
		else{
			$this->Session->setFlash(__('Product was not deleted', true));
			$this->redirect(array('action' => 'index'));
		}

		if ($this->Product->delete($id, true)) {
			$this->Session->setFlash(__('Product deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		else{
			$this->Session->setFlash(__('Product was not deleted', true));
			$this->redirect(array('action' => 'index'));
		}
	}//end og delete

	function getSimilarProducts($products) {
		$result = array();
		$pid = array();
		foreach($products as $p) {
			$pid[] = $p['Product']['id'];
		}

		$users = $this->Buyhistory->find('all', array(
			'conditions' => array('Buyhistory.product_id' => $pid),
			'fields' => 'Buyhistory.user_id',
			'limit' => 5,
		));
		$uid = array();
		foreach($users as $u) {
			$uid[] = $u['Buyhistory']['user_id'];
		}

		if (!isset($pid[0])) $p = 7;
		else $p = $pid[0];

		$related = $this->Buyhistory->find('all', array(
			'conditions' => array('Buyhistory.user_id' => $uid, 'Buyhistory.product_id != ' => $p),
			'fields' => array('Product.id', 'Product.image', 'Product.name'),
			'limit' => 4,
			'order' => 'Buyhistory.created DESC',
			'group' => 'Product.id'
		));
		return $related;
	}

	function recommendation() {
		$recommends = array();
		$user = $this->Auth->user();
		$this->Product->recursive = 0;
		if ($user) {
			$recently_view_products = $this->Viewhistory->find('all', array(
				'conditions' => array('Viewhistory.user_id' => $user['User']['id']),
				'fields' => array('Product.id', 'Product.image', 'Product.name'),
				'limit' => 3,
				'order' => 'Viewhistory.created DESC'
			));
			$recently_buy_products = $this->Buyhistory->find('all', array(
				'conditions' => array('Buyhistory.user_id' => $user['User']['id']),
				'fields' => array('Product.id', 'Product.image', 'Product.name'),
				'limit' => 3,
				'order' => 'Buyhistory.created DESC'
			));
			$best_selling = $this->Product->find('all', array(
				'fields' => array('Product.id', 'Product.image', 'Product.name'),
				'order' => array('Product.rating DESC'),
				'limit' => 5
			));
			$recommends = array_merge($recently_view_products, $best_selling, $this->getSimilarProducts($recently_buy_products));
		} else {
			$best_selling = $this->Product->find('all', array(
				'fields' => array('name', 'image', 'id'),
				'order' => array('Product.rating DESC'),
				'limit' => 5
			));
			$most_viewed = $this->Product->find('all', array(
				'fields' => array('name', 'image', 'id'),
				'order' => array('Product.view_count DESC'),
				'limit' => 5
			));
			$recommends = array_merge($best_selling, $most_viewed);
		}
		$this->Product->recursive = 1;
		shuffle($recommends);
		$recommends = array_map('unserialize', array_unique(array_map('serialize', $recommends)));
		if (count($recommends) > 20) {
			$recommends = array_splice($recommends, 20);
		}
		$this->set(compact('recommends'));
	}
	function aboutus() {
	}

	function contact() {
	}
}
	
?>
